package cn.itsnkkka.utils;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class KryoUtils {

    private static final ThreadLocal<Kryo> kryoLocal = ThreadLocal.withInitial(() -> {
        Kryo kryo = new Kryo();
        kryo.setRegistrationRequired(false);
        return kryo;
    });

    /**
     * 获取当前线程实例
     */
    private static Kryo getInstance() {
        return kryoLocal.get();
    }

    /**
     * 将【对象】 序列化为字节数组
     * @param object 任意对象
     * @return 字节数组
     */
    public static byte[] writeToByteArray(Object object) throws IOException {
        try (
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            Output output = new Output(byteArrayOutputStream);
        ) {
            Kryo kryo = getInstance();
            kryo.writeClassAndObject(output, object);
            output.flush();
            return byteArrayOutputStream.toByteArray();
        }
    }

    /**
     * 将字节数组返序列化为原对象
     * @param bytes 字节数组
     * @param <T>  对象类型
     */
    public static <T> T readFromByteArray(byte[] bytes, Class<T> tClass) throws IOException {
        try (
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            Input input = new Input(byteArrayInputStream)
        ) {
            Kryo kryo = getInstance();
            return tClass.cast(kryo.readClassAndObject(input));
        }
    }


}
